package com.dd.common.base

import android.util.Log
import com.dd.lnetwork.exception.ERROR
import com.dd.lnetwork.exception.ResponseThrowable
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable

abstract class BaseSubscriber<T : Any>(
    private var subscriberListener: SubscriberListener?,
    private var isShowDialog: Boolean = true
) : Observer<T> {

    private var functionCallback: CommonCallback<Disposable>? = null

    /**
     * 设置开始回调，用于获取Disposable
     *
     * @param callback
     */
    fun setFunctionCallback(callback: CommonCallback<Disposable>) {
        functionCallback = callback
    }


    override fun onSubscribe(s: Disposable) {
        functionCallback?.call(s)

        subscriberListener?.let {
            if (isShowDialog) {
                it.showProgress()
            }
        } ?: run {
            Log.e("BaseSubscriber", "BaseSubscriber mView == null ")
            onError(RuntimeException("BaseSubscriber mView == null"))
            return
        }
    }

    override fun onComplete() {
        subscriberListener?.let {
            it.onComplete()
            if (isShowDialog) {
                it.hideProgress()
            }
        } ?: run {
            return
        }
        subscriberListener = null
    }

    override fun onError(e: Throwable) {
        subscriberListener?.let { listener ->
            listener.onComplete()
            if (e is ResponseThrowable) {
                showError(e)
            } else {
                showError(ResponseThrowable(e, ERROR.UNKNOWN))
            }
            if (isShowDialog) {
                listener.hideProgress()
            }
        } ?: return

        subscriberListener = null
    }

    private fun showError(e: ResponseThrowable) {
        subscriberListener?.let {
            if (e.code == ERROR.ERROR_UN_LOGIN) {
                it.showNotice(ERROR.ERROR_UN_LOGIN, "")
            } else {
                e.message?.let { error ->
                    it.showNotice(ERROR.ERROR_API, error)
                }
            }
        }
    }


    interface SubscriberListener {
        fun showProgress()
        fun hideProgress()
        fun showNotice(type: Int, msg: String)
        fun onComplete()
    }

    class SubscriberCallback : SubscriberListener {
        override fun showProgress() {}
        override fun hideProgress() {}
        override fun showNotice(type: Int, msg: String) {}
        override fun onComplete() {}
    }
}